/**
 * 
 */
package belote.webapp.struts.user;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

import belote.service.user.User;
import belote.service.user.UserService;
import belote.service.user.UserServiceFactory;
import belote.webapp.WebappConstants;

/**
 * @author Gwenn
 * 
 */
public class LoginAction extends Action {

	private final UserService userService = UserServiceFactory.getUserService();

	private static final int COOKIE_EXPIRY = 60 * 60 * 24 * 30; // 30 jours

	/**
	 * {@inheritDoc}
	 */
	@Override
	public ActionForward execute(ActionMapping pMapping, ActionForm pForm, HttpServletRequest pRequest, HttpServletResponse pResponse) throws Exception {

		LoginForm loginForm = (LoginForm) pForm;

		User user = userService.selectByLoginPassword(loginForm.getLogin(), loginForm.getPassword());
		if (user != null) {

			// On stock l'utilisateur en session
			HttpSession session = pRequest.getSession();
			session.setAttribute(WebappConstants.SESSION.USER, user);

			// Si la case 'remember' est cochee, on créé un cookie avec l'id
			// user.
			if (loginForm.isRemember()) {

				Cookie cookie = new Cookie(WebappConstants.COOKIE.REMEMBER, Long.toString(user.getId()));
				cookie.setPath("/");
				cookie.setMaxAge(COOKIE_EXPIRY);

				pResponse.addCookie(cookie);
			}

			return pMapping.findForward(WebappConstants.FORWARD.HOME_REDIRECT);

		} else {

			ActionErrors errors = new ActionErrors();
			errors.add("global", new ActionMessage("login.form.global.loginPasswordInvalid"));
			addErrors(pRequest, errors);

			return pMapping.getInputForward();
		}
	}
}
